package com.bdk.middle.common.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * <h1>AES加密</h1>
 * <p>只实现了ECB模式128位加密和解密</p>
 *
 * @author kui
 */
public class AESUtil {

    private static Logger logger = LoggerFactory.getLogger(AESUtil.class.getName());

    /**
     * AES加密
     *
     * @param data   加密数据
     * @param keyStr 加密key
     * @return java.lang.String
     */
    public static String encrypt(String data, String keyStr) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(keyStr.getBytes("UTF-8"), "AES");
            cipher.init(1, key);
            return Base64.encodeBase64String(cipher.doFinal(data.getBytes("UTF-8")));
        } catch (Exception e) {
            logger.debug("AES加密失败\ninfo:" + e.getMessage());
        }
        return "";
    }

    /**
     * AES解密
     *
     * @param base64Data 解密内容
     * @param keyStr     解密Key
     * @return java.lang.String
     */
    public static String decrypt(String base64Data, String keyStr) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(keyStr.getBytes("UTF-8"), "AES");
            cipher.init(2, key);
            return new String(cipher.doFinal(Base64.decodeBase64(base64Data)));
        } catch (Exception e) {
            logger.debug("AES解密失败\ninfo: " + e.getMessage());
        }
        return "";
    }

}
